package com.atguigu.gmall.pay.api;

import com.atguigu.gmall.feign.order.OrderFeignClient;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.pay.service.PayService;
import com.atguigu.gmall.pay.vo.PayParamsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

@RequestMapping("/api/payment")
@RestController
public class PayController {

    @Autowired
    PayService payService;
    @Autowired
    OrderFeignClient orderFeignClient;

    /**
     * 去支付宝查询一个订单是否支付了
     * 1： 支付成功
     * 0:  其他状态
     * @param outTradeNo
     * @return
     */
    @GetMapping("/status/{outTradeNo}")
    public String queryOrderPayStatus(@PathVariable("outTradeNo") String outTradeNo) throws Exception {
        Boolean orderStatus = payService.queryOrderStatus(outTradeNo);
        return orderStatus ? "1":"0";
    }

    /**
     * 收到来自于前端页面，点击扫码支付。
     * @param id
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/alipay/submit/{orderId}", produces = "text/html")
    public String payment(@PathVariable("orderId") Long id) throws Exception {
        PayParamsVo vo = new PayParamsVo();

        OrderInfo orderById = orderFeignClient.getOrderById(id);
        vo.setTotal_amount(orderById.getTotalAmount().toString());
        vo.setOut_trade_no(orderById.getOutTradeNo().toString());
        vo.setSubject(orderById.getConsignee() + "的订单");
        vo.setBody(orderById.getOrderComment());

        //2016-12-31 10:05:01，支付宝的自动收单。支付宝订单过期时间就是我们数据库中保存的订单过期时间
        Date expireTime = orderById.getExpireTime();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        vo.setTime_expire(dateFormat.format(expireTime));

        //调用支付
        String result = payService.payOrder(vo);
        return result;
    }
}
